package org.skydiveapp2;

import org.skydiveapp2.ui.InterfaceManager;
import org.skydiveapplibrary.repository.LocationRepository;
import org.skydiveapplibrary.ui.LocationListAdapter;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

public class LocationListActivity extends BaseListActivity
{
    @Override 
    public void onCreate(Bundle savedInstanceState)
    { 
    	super.onCreate(savedInstanceState);
    	
    	overridePendingTransition(R.anim.fadein,
                R.anim.hold);
    	
    	getListView().setChoiceMode(ListView.CHOICE_MODE_NONE);
    	
		if (this.findViewById(R.id.tabletLayout) != null)
		{
			InterfaceManager.getInstance().configureTabletUI(this, 
					R.string.locations_label);
		}
		else
		{
			InterfaceManager.getInstance().configurePhoneUI(this, 
					R.string.locations_label);
		}
    	
    	loadData();
    }
    
    @Override
    public void onListItemClick(ListView lv, View view, int position, long id)
    {
    	Intent intent = new Intent(this, LocationEditActivity.class);
        intent.putExtra(Constants.EXTRA_LOCATION_ID, (int)id);
        startActivity(intent);    	
    }
    
    private void loadData()
    {
    	// populate
		LocationRepository repository = new LocationRepository(this);
		LocationListAdapter adapter = new LocationListAdapter(
				this,
				repository.getLocations());
		setListAdapter(adapter);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_add, menu);
        inflater.inflate(R.menu.menu_back, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        // Handle item selection
        switch (item.getItemId())
        {
        case R.id.menu_add:
        	Intent intent = new Intent(this, LocationEditActivity.class);
            startActivity(intent);
            return true;
            
        case R.id.menu_back:
        	close();
        	return true;
        
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
	@Override
    public void onBackPressed() {
		close();
    }
	
	private void close()
	{
		finish();
    	overridePendingTransition(R.anim.hold,
                R.anim.fadeout);
	}
} 